/**
 * 公共JavaScript函数库
 * 相对路径: inc/pubs.js
 * 作者: 15058593138@qq.com
 */

// Ajax通信函数
function ajax(url, data, callback, method = 'POST') {
    const xhr = new XMLHttpRequest();
    
    if (method === 'GET' && data) {
        url += '?' + toQueryString(data);
        data = null;
    }
    
    xhr.open(method, url, true);
    
    if (method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        data = toQueryString(data);
    }
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const res = JSON.parse(xhr.responseText);
                    callback(res);
                } catch (e) {
                    toast('响应格式错误', 'error');
                }
            } else {
                toast('网络请求失败', 'error');
            }
        }
    };
    
    xhr.send(data);
}

// 对象转查询字符串
function toQueryString(obj) {
    if (!obj) return '';
    const pairs = [];
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
        }
    }
    return pairs.join('&');
}

// 获取表单数据
function getFormData(formId) {
    const form = document.getElementById(formId);
    if (!form) return {};
    
    const data = {};
    const elements = form.elements;
    
    for (let i = 0; i < elements.length; i++) {
        const el = elements[i];
        if (el.name && !el.disabled) {
            if (el.type === 'checkbox') {
                data[el.name] = el.checked ? 1 : 0;
            } else if (el.type === 'radio') {
                if (el.checked) {
                    data[el.name] = el.value;
                }
            } else {
                data[el.name] = el.value;
            }
        }
    }
    
    return data;
}

// 吐司提示
function toast(msg, type = 'info', duration = 3000) {
    const toast = document.createElement('div');
    toast.className = 'toast ' + type;
    toast.textContent = msg;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, duration);
}

// 显示遮罩层
function showModal(title, content, buttons = []) {
    let modal = document.getElementById('globalModal');
    
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'globalModal';
        modal.className = 'modal';
        document.body.appendChild(modal);
    }
    
    let buttonHtml = '';
    buttons.forEach(btn => {
        buttonHtml += `<button class="btn ${btn.class}" onclick="${btn.onclick}">${btn.text}</button>`;
    });
    
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3>${title}</h3>
                <span class="modal-close" onclick="closeModal()">&times;</span>
            </div>
            <div class="modal-body">${content}</div>
            ${buttons.length > 0 ? `<div class="modal-footer">${buttonHtml}</div>` : ''}
        </div>
    `;
    
    modal.classList.add('show');
    
    // 点击背景关闭
    modal.onclick = function(e) {
        if (e.target === modal) {
            closeModal();
        }
    };
}

// 关闭遮罩层
function closeModal() {
    const modal = document.getElementById('globalModal');
    if (modal) {
        modal.classList.remove('show');
    }
}

// 确认对话框
function confirm(msg, callback) {
    showModal('确认', `<p>${msg}</p>`, [
        {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
        {text: '确定', class: 'btn-primary', onclick: 'closeModal();(' + callback.toString() + ')()'}
    ]);
}

// 分页函数
function pagination(page, total, callback) {
    const maxPage = Math.ceil(total / window.pageSize);
    if (maxPage <= 0) return '';
    
    let html = '<div class="pagination">';
    
    // 首页
    if (page > 1) {
        html += `<a href="javascript:${callback}(1)">首页</a>`;
        html += `<a href="javascript:${callback}(${page - 1})">上一页</a>`;
    } else {
        html += '<a class="disabled">首页</a>';
        html += '<a class="disabled">上一页</a>';
    }
    
    // 页码选择
    html += '<select onchange="' + callback + '(this.value)">';
    for (let i = 1; i <= maxPage; i++) {
        html += `<option value="${i}" ${i === page ? 'selected' : ''}>第${i}页</option>`;
    }
    html += '</select>';
    
    // 尾页
    if (page < maxPage) {
        html += `<a href="javascript:${callback}(${page + 1})">下一页</a>`;
        html += `<a href="javascript:${callback}(${maxPage})">末页</a>`;
    } else {
        html += '<a class="disabled">下一页</a>';
        html += '<a class="disabled">末页</a>';
    }
    
    html += `<span>共${total}条</span>`;
    html += '</div>';
    
    return html;
}

// 格式化日期
function formatDate(date, format = 'Y-m-d H:i:s') {
    if (typeof date === 'string') {
        date = new Date(date);
    }
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    
    return format
        .replace('Y', year)
        .replace('m', month)
        .replace('d', day)
        .replace('H', hour)
        .replace('i', minute)
        .replace('s', second);
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            func.apply(context, args);
        }, wait);
    };
}

// 加载中效果
function showLoading() {
    const loading = document.createElement('div');
    loading.id = 'globalLoading';
    loading.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;z-index:9999;';
    loading.innerHTML = '<div style="background:#fff;padding:20px;border-radius:5px;font-size:16px;">加载中...</div>';
    document.body.appendChild(loading);
}

function hideLoading() {
    const loading = document.getElementById('globalLoading');
    if (loading) {
        loading.remove();
    }
}